<?php

namespace App\Console\Commands;

use App\Business\BLL\Wechat\Official;
use App\Models\WechatUser;
use Illuminate\Console\Command;

class UpdateUserWechatOpenid extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'update:wechatopenid';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新用户表中缺少公众号openid的用户';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $official = Official::make();
        $list = $official->user->list();
        $list = $list['data']['openid'];
        foreach ($list as $vo) {
            $user = WechatUser::where('wechat_openid', $vo)->first();
            if (!$user) {
                $wechatUserInfo = $official->user->get($vo);
                $user = WechatUser::firstOrCreate(
                    [
                        'unionid' => $wechatUserInfo['unionid'],
                    ]
                    , [
                        'wechat_openid' => $wechatUserInfo['openid'],
                        'name' => $wechatUserInfo['nickname'],
                        'head_img' => $wechatUserInfo['headimgurl'],
                    ]
                );
                if (empty($user->wechat_openid)) {
                    $user->wechat_openid = $wechatUserInfo['openid'];
                    $user->save();
                }
            }
        }

    }
}
